import 'dart:convert';
import 'dart:ffi';
import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:lf_product_plugin/lf_product_plugin.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'wait';
  String _hello = 'wait';
  dynamic _bodyFat = 'wait';
  dynamic _bodyFat8 = 'wait';
  dynamic _scan = 'wait';
  dynamic _link = 'wait';
  dynamic _weight = 0.0;
  dynamic _lock_weight = 0.0;

  final List<Map<String, dynamic>> _devices = []; // 存储唯一设备
  final Set<String> _deviceMacSet = {}; // 记录已添加的 deviceMac

  final _lfProductPlugin = LfProductPlugin();

  @override
  void initState() {
    super.initState();
    _lfProductPlugin.onListening((event) {
      print('------- platform event -----------');
      print(event);

      //{find_new_device: {rssi: -71, deviceMac: CF:E8:03:20:D0:73, sdkCode: 0, devicePower: 35, deviceType: 1, deviceName: CF577, devicePowerType: 3, deviceCalcuteType: 12, standardType: 0, advLength: 999, avatarType: 0, deviceConnectType: 2, sign: 01, deviceAccuracyType: 2, deviceSettingId: 177, PeripheralType: 8, deviceUnitList: 0,1,11, deviceFuncType: 73951, macAddressStart: 6, deviceProtocolType: 3}}

      Map<String, dynamic> parsedData = Map<String, dynamic>.from(event);
      //发现新设备
      if (parsedData.containsKey("find_new_device")) {
        Map<String, dynamic> new_device_info =
            Map<String, dynamic>.from(parsedData["find_new_device"]);
        if (!_deviceMacSet.contains(new_device_info["deviceMac"])) {
          setState(() {
            _devices.add(new_device_info);
            _deviceMacSet.add(new_device_info["deviceMac"]);
          });
        }
      }
      //实时体重
      if (parsedData.containsKey("unlock_weight")) {
        setState(() {
          _weight = parsedData["unlock_weight"];
        });
      }
      //锁定体重
      if (parsedData.containsKey("lock_weight")) {
        setState(() {
          _lock_weight = parsedData["lock_weight"];
        });
      }
    });
  }

  Future<void> callReset() async {
    setState(() {
      _platformVersion = 'wait';
      _hello = 'wait';
      _bodyFat = 'wait';
      _bodyFat8 = 'wait';
      _weight = 0.0;
      _lock_weight = 0.0;
    });
  }

  Future<void> callNativeV() async {
    try {
      String platformVersion = await _lfProductPlugin.getPlatformVersion() ??
          'Unknown platform version';
      setState(() {
        _platformVersion = platformVersion;
      });
    } on PlatformException {
      setState(() {
        _platformVersion = 'Failed to call platform method';
      });
    }
  }

  Future<void> callNativeHello() async {
    try {
      String hello = await _lfProductPlugin.getHelloWorld() ?? 'error hello';
      setState(() {
        _hello = hello;
      });
    } on PlatformException {
      setState(() {
        _hello = 'Failed to call hello method';
      });
    }
  }

  Future<void> callNativeC4() async {
    try {
      String result = await _lfProductPlugin.calculate4(
        height: 180, // 身高 (cm)
        weight: 70.12, // 体重 (kg)
        heartRate: 60.0, // 心跳
        impendance: 419, // 电阻 (Ω)
        age: 28,
        gender: 0, // 男性
      );
      setState(() {
        _bodyFat = result;
      });
    } on PlatformException {
      setState(() {
        _bodyFat = 'Failed to call callNativeC4 method';
      });
    }
  }

  Future<void> callNativeC8() async {
    try {
      String result8 = await _lfProductPlugin.calculate8(
        height: 170, // 身高 (cm)
        weight: 66.25, // 体重 (kg)
        heartRate: 70, // 心跳
        age: 28,
        gender: 0, // 男性
        z100KhzLeftArmEnCode: 1343012553,
        z100KhzLeftLegEnCode: 537483970,
        z100KhzRightArmEnCode: 1348207576,
        z100KhzRightLegEnCode: 1888092345,
        z100KhzTrunkEnCode: 808605405,
        z20KhzLeftArmEnCode: 3025280,
        z20KhzLeftLegEnCode: 1889350941,
        z20KhzRightArmEnCode: 1102073564,
        z20KhzRightLegEnCode: 540921544,
        z20KhzTrunkEnCode: 1349589316,
      );
      setState(() {
        _bodyFat8 = result8;
      });
    } on PlatformException {
      setState(() {
        _bodyFat8 = 'Failed to call callNativeC8 method';
      });
    }
  }

  Future<void> callNativeS() async {
    try {
      bool permission = await requestNearDevicePermission(context);

      if (permission) {
        String? scan = await _lfProductPlugin.scan();
        setState(() {
          _scan = scan;
        });
      }
    } on PlatformException {
      setState(() {
        _scan = 'Failed to call callNativeS method';
      });
    }
  }

  Future<void> callNativeL(dynamic) async {
    print('callNativeL');
    try {
      String? link = await _lfProductPlugin.link(device: dynamic);
      setState(() {
        _link = link;
      });
    } on PlatformException {
      setState(() {
        _link = 'Failed to call callNativeL method';
      });
    }
  }

  Future<void> callNativeR() async {
    Map<String, dynamic> deviceData = {
      "rssi": -71,
      "deviceMac": "CF:E8:03:20:D0:73",
      "sdkCode": 0,
      "devicePower": 35,
      "deviceType": 1,
      "deviceName": "CF577",
      "devicePowerType": 3,
      "deviceCalcuteType": 12,
      "standardType": 0,
      "advLength": 999,
      "avatarType": 0,
      "deviceConnectType": 2,
      "sign": "01",
      "deviceAccuracyType": 2,
      "deviceSettingId": 177,
      "PeripheralType": 8,
      "deviceUnitList": "0,1,11",
      "deviceFuncType": 73951,
      "macAddressStart": 6,
      "deviceProtocolType": 3
    };
    setState(() {
      _devices.add(deviceData);
      _deviceMacSet.add(deviceData["deviceMac"]);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Lefu Plugin example app'),
        ),
        body: SingleChildScrollView(
            child: Column(children: [
          CustomButton(onPressed: callReset, text: '重置'),
          CustomButton(onPressed: callNativeV, text: '版本号'),
          CustomButton(onPressed: callNativeHello, text: 'Hello'),
          CustomButton(onPressed: callNativeC4, text: '4电极'),
          CustomButton(onPressed: callNativeC8, text: '8电极'),
          CustomButton(onPressed: callNativeS, text: '扫描'),
          CustomButton(onPressed: callNativeR, text: '模拟'),
          Text('Running on: $_platformVersion\n'),
          Text('测试: $_hello\n'),
          Text('4电极: $_bodyFat\n'),
          Text('8电极: $_bodyFat8\n'),
          Text('扫描: $_scan\n'),
          Text('连接: $_link\n'),
          Text('实时体重: $_weight\n'),
          Text('锁定体重: $_lock_weight\n'),
          ListView.builder(
            shrinkWrap: true, // 解决不显示问题
            physics: const NeverScrollableScrollPhysics(), // 禁止内部滚动
            itemCount: _devices.length,
            itemBuilder: (context, index) {
              var device = _devices[index];
              return ListTile(
                title: Text(device["deviceName"]),
                subtitle: Text(device["deviceMac"]),
                onTap: () => callNativeL(device),
              );
            },
          ),
        ])),
      ),
    );
  }
}

class CustomButton extends StatelessWidget {
  final VoidCallback onPressed;
  final String text;

  const CustomButton({
    super.key,
    required this.onPressed,
    required this.text,
  });

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity, // 按钮宽度固定为 300px
      child: ElevatedButton(
        onPressed: onPressed,
        child: Text(text),
      ),
    );
  }
}

// 申请蓝牙权限
Future<bool> requestNearDevicePermission(BuildContext context,
    {Function? confirm, Function? cancel}) async {
  if (Platform.isAndroid) {
    // PermissionStatus status = await Permission.bluetooth.status;

    PermissionStatus status = await Permission.bluetoothScan.request();
    PermissionStatus status1 = await Permission.bluetoothConnect.request();

    PermissionStatus loctionStatus =
        await Permission.locationWhenInUse.request();

    bool isPermission = false;
    //String androidVersion = androidInfo.version.release;
    bool isAndroidVersionGreaterThan12 =
        await getNearVersion(); //androidVersion.compareTo('12') > 0;
    if (isAndroidVersionGreaterThan12) {
      isPermission = status.isGranted && status1.isGranted;
    } else {
      isPermission = loctionStatus.isGranted;
    }
    return isPermission;
  }
  return true;
}

Future<bool> getNearVersion() async {
  DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
  AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
  bool isAndroidVersionGreaterThan12 = androidInfo.version.sdkInt >= 31;
  return isAndroidVersionGreaterThan12;
}
